﻿using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
using Microsoft.Windows.AppLifecycle;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Windows.ApplicationModel.Activation;
using Windows.Storage;
using DNFImagePacks2Manager.Helpers;
using Microsoft.UI.Xaml.Controls;
using System.IO;

namespace DNFImagePacks2Manager
{
    // 应用主类
    public partial class App : Application
    {
        // 主窗口实例
        private static MainWindow? m_window;

        // 关联文件打开防重
        private static string latestFilesPath = "";
        private static readonly object _filePathLock = new();

        // 应用构造方法
        public App()
        {
            // 启动时异常捕获
            try
            {

                InitializeComponent();
            }
            catch (Exception ex)
            {
                File.WriteAllText(@"C:\temp\app_startup_error.log", ex.ToString());
            }
        }

        // 获取主窗口实例
        public static MainWindow? GetMainWindow()
        {
            return m_window;
        }

        // 启动事件
        protected override async void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
        {
            // 启动时异常捕获
            try
            {
                // 单例模式
                string instanceKey = "DNFImagePacks2Manager_Instance";
                var activation = AppInstance.FindOrRegisterForKey(instanceKey);

                if (!activation.IsCurrent)
                {
                    // 转发事件到唯一实例
                    var activatedEventArgs = AppInstance.GetCurrent().GetActivatedEventArgs();
                    await activation.RedirectActivationToAsync(activatedEventArgs);
                    Process.GetCurrentProcess().Kill();
                    return;
                }

                activation.Activated += MainInstance_Activated;

                HandleActivation(AppInstance.GetCurrent().GetActivatedEventArgs());
            }
            catch (Exception ex)
            {
                File.WriteAllText(@"C:\temp\app_startup_error.log", ex.ToString());
                if (m_window != null)
                {
                    var dialog = new ContentDialog
                    {
                        Title = "启动失败",
                        Content = ex.Message,
                        CloseButtonText = "确定",
                        XamlRoot = m_window?.Content.XamlRoot
                    };
                    await dialog.ShowAsync();
                }
            }
        }

        // 主实例激活事件
        private void MainInstance_Activated(object? sender, AppActivationArguments e)
        {
            HandleActivation(e);
        }

        private static void HandleActivation(AppActivationArguments args)
        {
            // 获取打开的文件
            List<StorageFile> files = [];

            if (args.Kind == ExtendedActivationKind.File)
            {
                var fileArgs = args.Data as FileActivatedEventArgs;
                if (fileArgs?.Files != null)
                {
                    StorageFile file = fileArgs.Files.OfType<StorageFile>().First();
                    string filePath = file.Path;

                    lock (_filePathLock)
                    {
                        if (!string.Equals(latestFilesPath, filePath))
                        {
                            latestFilesPath = filePath;
                            files.Add(file);
                        }
                    }
                }
            }

            // 获取主实例线程
            var dispatcherQueue = DispatcherQueue.GetForCurrentThread() ?? m_window?.DispatcherQueue;
            if (dispatcherQueue == null) {
                return;
            }

            dispatcherQueue.TryEnqueue(async () =>
            {
                // 如果主窗口实例为空则为首次启动
                bool firstBoot = false;
                if (m_window == null)
                {
                    m_window = new MainWindow();
                    firstBoot = true;
                }
                // 激活窗口
                m_window.Activate();

                // 判断是否有需要导入的文件
                if (files.Count > 0)
                    // 导入打开的文件
                    m_window.ChangeProcessLoadPage(files);
                else if (firstBoot)
                    // 如果是首次启动则进入主页
                    m_window.ChangePage("Home");
                    //m_window.ChangePage("Settings");

                // 更新检查
                if (firstBoot)
                {
                    if (LocalStorageHelper.GetAutoUpdateCheckEnable())
                    {
                        Page? currentPage = m_window.CurrentPage;
                        if (currentPage != null) {
                            await VersionHelper.UpdateCheck(currentPage, true);
                        }
                    }
                }
            });
        }
    }
}